close all; 
clear clc; 
S = 'abcd';
P = [0.1, 0.4, 0.2, 0.3];     
str = 'cadacdb';
l = 0;     
r = 1;     
d = 1;  
n = length(str);     
n_S = length(P);     
%**********处理第一个字符***********%     
for i=1:n         
    flag = 0;         
    for k = 1:n_S 
            if str(i)==S(k)                 
                m=k;                 
                flag =1;                 
                break;             
            end
    end
        if flag ==0 
            error('非信源字符');         
        end  
%*********当前单个字符的左、右端以及长度处理**************%         
        pl = 0;         
        pr = 0; 
        for j = 1:m-1 
            pl = pl + P(j);    %左端         
        end 
        pr = pl+P(m);     %右端  
        pd = pr - pl;         %子区间长度  
%*********新子区间的左、右边界以及长度处理**************%         
        if i == 1            %首字符             
            l = pl;             
            r = pr;             
            d = pd; 
        else              %算术编码规则             
            l = l+d*pl;                       
            d = d*pd;             
            r = l+d;         
        end          
        format long;     
end 
strl = strcat('编码结果：');     
disp(strl);     
format long;     
disp((l+r)/2);
    